const DouyinParser = require('./rule/DouyinParser');
const XhslinkParser = require('./rule/XhslinkParser');
const KuaishouParser = require('./rule/KuaishouParser');
const BilibiliParser = require('./rule/BilibiliParser');
class UniversalVideoParser {
  constructor() {
    this.platforms = {
      'kuaishou': new KuaishouParser(),
      'douyin': new DouyinParser(),
      'xhslink': new XhslinkParser(),
      // 'tiktok': new TiktokParser(),
      'bilibili': new BilibiliParser(),
      // 'weibo': new WeiboParser()
    };


  }


  // 检测平台类型
  detectPlatform(url) {
    const patterns = {
      kuaishou: /kuaishou|ks\./i,
      douyin: /douyin|iesdouyin/i,
      tiktok: /tiktok/i,
      bilibili: /bilibili|b23\.tv/i,
      weibo: /weibo/i,
      xhslink: /xhslink/i,
    };

    for (const [platform, pattern] of Object.entries(patterns)) {
      if (pattern.test(url)) {
        return platform;
      }
    }
    return 'unknown';
  }

  // 主解析方法
  async parseVideo(url, options = {}) {
    const { useThirdParty = true, useSelfParse = true, timeout = 15000 } = options;
    const platform = this.detectPlatform(url);
    // 2. 使用平台专用解析器
    if (useSelfParse && this.platforms[platform]) {
      try {
        const videoUrl = await this.platforms[platform].parse(url, timeout);
        console.log(`自建${platform}解析器成功:`, videoUrl);
        return videoUrl.data
        if (videoUrl) return { success: true, platform, url: videoUrl, source: 'self_parse' };
      } catch (error) {
        console.log(`自建${platform}解析器失败:`, error.message);
      }
    }

    // // 3. 通用解析尝试
    // try {
    //   const videoUrl = await this.genericParse(url, timeout);
    //   if (videoUrl) return { success: true, platform, url: videoUrl, source: 'generic' };
    // } catch (error) {
    //   console.log('通用解析失败:', error.message);
    // }

    // return { success: false, platform, error: '所有解析方法都失败了' };
  }



  // // 从API响应中提取视频URL
  // extractVideoUrlFromResponse(data) {
  //   if (typeof data === 'string') {
  //     try {
  //       const jsonData = JSON.parse(data);
  //       return jsonData.url || jsonData.video_url || jsonData.data?.url;
  //     } catch (e) {
  //       if (data.startsWith('http')) {
  //         return data;
  //       }
  //     }
  //   } else if (typeof data === 'object') {
  //     return data.url || data.video_url || data.data?.url;
  //   }
  //   return null;
  // }

}

module.exports = UniversalVideoParser;